/* 
 * File: Pool
 * Created: 13-JUN-2011
 * Author: Colin Gall-McDaid
 * 
 * Description: Instance pooling class. Avoid the frequent creation of new class
 * instances by re-using previously created instances. Stops too much garbage
 * collection from occuring.
 */
package com.gallsoft.games.framework;

import java.util.ArrayList;
import java.util.List;


public class Pool<T> {

    /**
     * Generic interface to return a new generic object from the Pool
     * @author Colin Gall-McDaid
     * @param <T> object type
     */
    public interface PoolObjectFactory<T> {
        public T createObject();
    }
    
    private final List<T> freeObjects;              // Pooled object store
    private final PoolObjectFactory<T> factory;     // Generate new instances
    private final int maxSize;                      // Max number of objects allowed
    
    /**
     * Constructor. 
     * 
     * @param factory object factory instance (determines object type)
     * @param maxSize maximum number of objects allowed
     */
    public Pool(PoolObjectFactory<T> factory, int maxSize) {
        this.factory = factory;
        this.maxSize = maxSize;
        this.freeObjects = new ArrayList<T>(maxSize);
    }
    
    /**
     * Get a new/used object from the pool.
     * 
     * @return the object
     */
    public T newObject() {
        T object = null;
        
        if (freeObjects.size() == 0)
            object = factory.createObject();
        else
            object = freeObjects.remove(freeObjects.size() - 1);
        
        return object;
    }
    
    /**
     * Add an object that is no longer used to the pool.
     * 
     * @param object the object to free up
     */
    public void free(T object) {
        if (freeObjects.size() < maxSize)
            freeObjects.add(object);
    }
}
